const { db, query } = require("../../db/db");
const util = require("util");

async function GetDialogueList(req, res) {
  let PageSize = req.body.PageSize || 10;
  let PageNum = req.body.PageNum || 1;
  let UserId = Number(req.params.username);
  let BeforeChatTime = req.body.BeforeChatTime || null; // 记录当前显示的最早一条记录的时间戳

  // 判断是否有传入 BeforeChatTime，如果有则说明是触上加载
  let select_list_sql;
  if (BeforeChatTime) {
    // 查询 BeforeChatTime 之前的聊天记录，按时间倒序排列
    select_list_sql = util.format(
      "SELECT \
        AiRecordId, \
        UserId, \
        IFNULL(ChatContent,'') as content, \
        IFNULL(ChatTime,'') as ChatTime, \
        IFNULL(Role,'') as role, \
        IsStop,\
        IsSatisfied \
      FROM Ai_Chat_Record \
      WHERE UserId=%s AND ChatTime < '%s' \
      ORDER BY ChatTime ASC, AiRecordId ASC \
      LIMIT %s",
      UserId,
      BeforeChatTime,
      PageSize
    );
  } else {
    // 默认情况下按时间倒序加载
    select_list_sql = util.format(
      "SELECT \
        AiRecordId, \
        UserId, \
        IFNULL(ChatContent,'') as content, \
        IFNULL(ChatTime,'') as ChatTime, \
        IFNULL(Role,'') as role, \
        IsStop,\
        IsSatisfied \
      FROM Ai_Chat_Record \
      WHERE UserId=%s \
      ORDER BY ChatTime DESC \
      LIMIT %s",
      UserId,
      PageSize
    );
  }

  const select_list_sql_res = await query(select_list_sql);

  // 获取总消息数
  const select_list_sql_count = util.format(
    "SELECT COUNT(*) as count \
     FROM Ai_Chat_Record \
     WHERE UserId=%s",
    UserId
  );

  const select_list_res_count = await query(select_list_sql_count);

  res.send({
    status: 0,
    AiDialogueList: BeforeChatTime
      ? select_list_sql_res
      : select_list_sql_res.reverse(),
    TotalCount: select_list_res_count[0].count,
  });
}

module.exports = { GetDialogueList };
